package model;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.DuplicateKeyException;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

import databeans.Likertq;
import interfas.LikertqInterface;

public class LikertqDAO implements LikertqInterface {

	private BeanFactory<Likertq> factory;
	
	public LikertqDAO() throws DAOException {
		try {
			BeanTable<Likertq> table = BeanTable.getInstance(Likertq.class, "likertq");
			if (!table.exists())
				table.create("qid");
			
			table.setIdleConnectionCleanup(true);
			factory = table.getFactory();
		} catch (BeanFactoryException e) {
			throw new DAOException(e);
		}
	}
	
	public void create(Likertq likertq, QuestionDAO questionDAO) throws DAOException {
		try {
			// Check for foreign key constraint
			if (questionDAO.lookup(likertq.getQid()) == null) {
				throw new DAOException("qid must exist in question table");
			}
			
			Transaction.begin();
			Likertq dbLikertq = factory.create(likertq.getQid());
			factory.copyInto(likertq, dbLikertq);
			Transaction.commit();
		} catch (DuplicateKeyException e) {
			throw new DAOException("A likertq with qid " + likertq.getQid() + " already exists");
		} catch (RollbackException e) {
			throw new DAOException(e);
		} finally {
			if (Transaction.isActive())
				Transaction.rollback();
		}
	}

	public Likertq lookup(int qid) throws DAOException {
		try {
			return factory.lookup(qid);
		} catch (RollbackException e) {
			throw new DAOException(e);
		}
	}
	
	public void delete(int qid) throws DAOException {
		try {
			Transaction.begin();
			Likertq dbLikertq = lookup(qid);
			if (dbLikertq == null)
				throw new DAOException("Likertq with qid " + qid + " doesn't exist");
			factory.delete(qid);
			Transaction.commit();
		} catch (RollbackException e) {
			throw new DAOException(e);
		} finally {
			if (Transaction.isActive())
				Transaction.rollback();
		}
	}

	public int size() throws DAOException {
		try {
			return factory.getBeanCount();
		} catch (RollbackException e) {
			throw new DAOException(e);
		}
	}
}
